package cn.pomit.springbootwork.oauthauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import cn.pomit.springbootwork.oauthauth.handler.AjaxAuthFailHandler;
import cn.pomit.springbootwork.oauthauth.handler.AuthSuccessHandler;
import cn.pomit.springbootwork.oauthauth.handler.AjaxLogoutSuccessHandler;
import cn.pomit.springbootwork.oauthauth.handler.UnauthorizedEntryPoint;
import cn.pomit.springbootwork.oauthauth.provider.SimpleAuthenticationProvider;

@Configuration
@EnableWebSecurity
public class AccessSecurityConfiguration extends WebSecurityConfigurerAdapter {
	@Autowired
	private SimpleAuthenticationProvider simpleAuthenticationProvider;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(simpleAuthenticationProvider);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.exceptionHandling()
				.authenticationEntryPoint(new UnauthorizedEntryPoint()).and()
				.csrf().disable()
				.authorizeRequests().antMatchers("/oauth/**").permitAll()
				.antMatchers("/").permitAll()
				.antMatchers("/index.html").permitAll()
				.antMatchers("/css/**").permitAll()
				.antMatchers("/js/**").permitAll()
				.antMatchers("/img/**").permitAll()
				.antMatchers("/api/**").authenticated()
				.and().formLogin()
				.loginPage("/login.html").usernameParameter("userName").passwordParameter("userPwd")
				.loginProcessingUrl("/login").successHandler(new AuthSuccessHandler())
				.failureHandler(new AjaxAuthFailHandler()).and()
				.logout().logoutUrl("/logout")
				.logoutSuccessHandler(new AjaxLogoutSuccessHandler());
	}
}
